package com.gitee.sparta.core.cluster.strategy;

import com.gitee.sparta.core.bean.cluster.ClusterProtocol;
import com.gitee.sparta.core.cluster.ClusterCache;
import com.gitee.sparta.core.cluster.balance.LoadBalance;
import com.gitee.sparta.core.property.SpartaCoreProperties;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;

import java.io.IOException;
import java.nio.channels.SocketChannel;

/**
 * <p>
 *      follower 宕机了，需要移除 follower
 * </p>
 *
 * @author zyred
 * @since v 0.0.2
 */
@Slf4j
public class FollowerShutdownStrategy extends Strategy {

    public FollowerShutdownStrategy(RedissonClient client,
                                   LoadBalance loadBalance,
                                   SpartaCoreProperties properties) {
        super(client, loadBalance, properties);
    }

    @Override
    public void handle(ChannelHandlerContext ctx, SocketChannel sc, ClusterProtocol cp) {
        log.info("[Sparta] Follower shutdown, sid: {}", cp.getServerId());
        this.loadBalance.removeNode(cp.getServerId());

        if (ClusterCache.isNetty()) {
            ClusterCache.removeCli(ctx.channel(), cp.getServerId());
            log.info("[Sparta] Netty channel closed : {}", ctx.channel().remoteAddress());
        } else {
            ClusterCache.removeCli(sc, cp.getServerId());
            try {
                log.info("[Sparta] Nio socket channel closed : {}", sc.getRemoteAddress());
            } catch (IOException e) {
                log.error("[Sparta] Nio socket channel error ...", e);
            }
        }
        super.removeToServerTable(cp.getServerId());
    }
}
